package server;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author bwcx_jzy
 * @since 2021/11/19
 */
public class MyClassLoader extends ClassLoader {

    private final File dir;

    public MyClassLoader(File dir) {
        this.dir = dir;
    }

    @Override
    protected Class<?> findClass(String name) {
        String myPath = new File(dir, name.replace(".", "/") + ".class").getAbsolutePath();
        byte[] cLassBytes;
        try {
            Path path = Paths.get(new URI("file://" + myPath));
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
            throw new NoClassDefFoundError(name);
        }
        return defineClass(name, cLassBytes, 0, cLassBytes.length);
    }

    @Override
    protected URL findResource(String name) {
        String myPath = new File(dir, name).getAbsolutePath();
        try {
            return new URL("file://" + myPath);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
